const model = require('../model/AdminModel.js')
const { genToken, verifyToken } = require('../utils/token.js')
let fs = require('fs')
let { PORT, SUCCESS_RESPONSE } = require('../config/index.js')
const excuteSql = require('../utils/query.js')

exports.logoInfo = async (req, res) => {
  let sql = 'select logo_title,logo_img from setting'
  let data = await excuteSql(sql)
  data[0].logo_img = `http://127.0.0.1:${PORT}/` + data[0].logo_img
  res.json(SUCCESS_RESPONSE(data[0]))
}

exports.login = async (req, res) => {
  let { username, password } = req.body
  // 真实业务中，肯定要去数据库中匹配
  let findUser = await model.Login(username, password)
  if (findUser.length > 0) {
    // 找到了，要生成JWT用户登录态（token字符串），返回给前端
    // '15000ms' '3h'
    let accessToken = genToken(
      { admin_id: findUser[0].admin_id, username: findUser[0].username },
      '3h'
    )
    let refreshToken = genToken(
      { admin_id: findUser[0].admin_id, username: findUser[0].username },
      '15d'
    )
    res.json({
      msg: '登录成功',
      data: { accessToken, refreshToken },
      code: '00000',
    })
  } else {
    res.json({ msg: '用户名或密码错误', code: '00001' })
  }
}

exports.updAvatar = async (req, res) => {
  // 1. 接收头像地址
  let { avatar } = req.body
  // 2. 将当前授权token中的admin_id进行更新
  let admin_id = req.admin_id
  // 3. 调用模型更新头像
  await model.updAvatar(admin_id, avatar)
  res.json(SUCCESS_RESPONSE({}, '更新用户头像成功'))
}

exports.upload = (req, res) => {
  // console.log(req.body) //接收文本信息
  console.log(req.file) //接收文件信息
  // 判断是否有文件上传
  if (req.file) {
    // 进行文件的重命名即可 fs.rename
    let { originalname, destination, filename } = req.file
    let dotIndex = originalname.lastIndexOf('.')
    let ext = originalname.substring(dotIndex)
    let oldPath = `${destination}${filename}`
    let newPath = `${destination}${filename}${ext}`
    fs.rename(oldPath, newPath, (err) => {
      if (err) {
        throw err
      }
      res.json({
        msg: '上传文件成功',
        data: { path: `${newPath}`, server_url: `http://127.0.0.1:${PORT}/` },
        code: '00000',
      })
    })
  } else {
    res.json({ msg: '没有文件', data: {}, code: '00089' })
  }
}

exports.adminInfo = async (req, res) => {
  // 1.获取用户id
  let admin_id = req.admin_id

  let data = await model.getUserInfo(admin_id)
  data[0].avatar = `http://127.0.0.1:${PORT}/` + data[0].avatar

  let userInfo = {
    code: '00000',
    data: { ...data[0] },
    msg: '获取用户信息成功',
  }
  res.json(userInfo)
}

exports.refreshToken = async (req, res) => {
  let { refreshToken } = req.body

  // 1. 验证refreshToken中的有效期
  let userInfo = verifyToken(refreshToken)
  if (userInfo === false) {
    // refreshToken失效了
    res.status(401).json({ msg: '用户refreshToken刷新失败', code: 'A0231' })
    return
  }
  // 2. 获取refreshToken中的用户信息,要去数据库查询最新的用户信息
  let result = await model.getAdminUserInfoById(userInfo.admin_id)
  if (result.length > 0) {
    let token = genToken(
      { admin_id: result[0].admin_id, username: result[0].username },
      '3h'
    )
    // 3. 重新再生成新token并返回给前端
    res.json({
      msg: '刷新token成功',
      data: { accessToken: token, refreshToken },
      code: '00000',
    })
  } else {
    res.json({
      message: '用户信息有误',
      code: 20003,
    })
  }
}

exports.adminList = async (req, res) => {
  const datas = await req.db.manager.findAll({
    raw: true,
    attributes: ['username', ['admin_id', 'adminId'], 'nickname'],
  })
  // 2. 响应给前端
  res.json({ code: '00000', msg: '获取管理员列表成功', data: datas })
}
